package com.ztjava.auth.controller.member;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.ztjava.auth.model.AuthMessage;
import com.ztjava.auth.model.AuthUser;
import com.ztjava.auth.service.AuthService;
import com.ztjava.auth.validator.LoginNoCaptchaValidator;
import com.ztjava.core.Constant;
import com.ztjava.core.Jsub;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.member.ApiClient;
import com.ztjava.ext.auth.annotation.AppMethod;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.ext.auth.annotation.UserMethod;
import com.ztjava.ext.auth.bean.AppSession;
import com.ztjava.ext.auth.bean.AuthSession;
import com.ztjava.ext.auth.tool.AuthTool;

@ControllerClass(path="/auth",client=ApiClient.class)
@UserController(portal=Constant.P_MEMBER,token=AuthTool.para)
public class AuthApiController extends BaseController{
	private static AuthService authService = Duang.duang(AuthService.class);
	
	@UserMethod
	public void logout(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AuthTool.removeUserSession(authSession);
		renderSuccess("注销成功！");
	}
	
	@AppMethod
	@Before({POST.class,LoginNoCaptchaValidator.class})
	public void getUserToken(){
		AuthUser authUser = getAttr("authUser");
		String token = AuthTool.createUserSession(authService.userToSession(authUser), 3600*24*7,null);
		AppSession appSession = getAttr(Constant.APPSESSION);
		String openid = HashKit.md5(Jsub.folder+"-"+appSession.getId()+"-"+authUser.getInt("id")) ;
		renderRet(Ret.create(Constant.RESULT,Constant.SUCCESS).set("token", token).set("expire",3600*24*7).set("openid",openid));
	}

	@UserMethod
	public void getMessageList(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		Page<AuthMessage> pd = authService.getMessagePage(client, setParaMap(getParaMapCustom(), "user_id", authSession.getId()));
		setAttr(Constant.RESULT, Constant.SUCCESS);
		setAttr(Constant.MESSAGE, "操作成功");
		setAttr("pd", pd);
		renderJson(new String[]{Constant.RESULT,Constant.MESSAGE,"pd"});
	}
	@UserMethod
	@Before({POST.class})
	public void updateMessageRead(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		String ids = getPara("ids");
		if(ids==null||ids.length()==0){
			Db.update("update "+AuthMessage.tablename+" set is_read='T' where user_id=? and is_read='F' ",authSession.getId());
		}else {
			Db.update("update "+AuthMessage.tablename+" set is_read='T' where user_id=? and is_read='F' and id in ("+ids+") ",authSession.getId());
		}
		renderSuccess("操作成功！");
	}
	
}
